<template>
  <div class="app-container">
    <el-container>
      <!-- 筛选区域 -->
      <el-header style="height: auto; padding: 10px;">
        <el-row :gutter="20" type="flex" align="middle">
          <!-- Website筛选 -->
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="5">
            <el-select
              v-model="web_id"
              v-loading="websLoading"
              style="width: 100%"
              size="small"
              placeholder="选择网站"
              clearable
              filterable
              @change="handleSearch"
            >
              <el-option
                v-for="web in webs"
                :key="web.id"
                :label="web.url"
                :value="web.id"
              />
            </el-select>
          </el-col>

          <!-- 关键词搜索 -->
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="5">
            <el-input
              v-model="kwInput"
              size="small"
              placeholder="搜索标题关键词"
              clearable
              @keyup.native.enter="handleSearch"
            >
              <el-button slot="append" size="small" icon="el-icon-search" @click="handleSearch">搜索</el-button>
            </el-input>
          </el-col>

          <!-- 进度筛选 -->
          <el-col :xs="24" :sm="24" :md="8" :lg="6" :xl="6">
            <div style="display: flex; align-items: center;">
              <span style="margin-right: 10px; white-space: nowrap;">完成进度:</span>
              <el-slider
                v-model="progress"
                range
                :format-tooltip="progressToolTips"
                :max="100"
                style="flex: 1;"
                @change="handleSearch"
              />
            </div>
          </el-col>

          <!-- 审核状态筛选 -->
          <el-col :xs="24" :sm="12" :md="8" :lg="4" :xl="4">
            <el-select v-model="review_state" size="small" placeholder="审核状态" @change="handleSearch">
              <el-option value="" label="所有状态" />
              <el-option
                v-for="item in review_states"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-col>

          <!-- 类型用途筛选 -->
          <el-col :xs="24" :sm="12" :md="8" :lg="4" :xl="4">
            <el-select
              v-model="category_id"
              v-loading="categoriesLoading"
              size="small"
              placeholder="类型用途"
              clearable
              @change="handleSearch"
            >
              <el-option
                v-for="category in categories"
                :key="category.id"
                :label="category.name"
                :value="category.id"
              />
            </el-select>
          </el-col>
        </el-row>
      </el-header>

      <!-- 主内容区域 -->
      <el-container>
        <el-main>
          <!-- 数据表格 -->
          <el-table
            v-loading.body="listLoading"
            :data="data"
            border
            fit
            highlight-current-row
            style="width: 100%"
          >
            <!-- ID列 -->
            <el-table-column align="center" label="ID" prop="id" width="80" />

            <!-- 标题列 -->
            <el-table-column align="left" label="标题" prop="title" min-width="350">
              <template slot-scope="scope">
                <div>
                  <span class="topic-title">{{ scope.row.title || scope.row.keyword }}</span>
                  <el-tag v-if="scope.row.category__name" size="mini" type="info" style="margin-left: 5px;">
                    {{ scope.row.category__name }}
                  </el-tag>
                </div>
              </template>
            </el-table-column>

            <!-- 父级标题列 -->
            <el-table-column align="left" label="父级标题" prop="parent__title" min-width="250">
              <template slot-scope="scope">
                <span v-if="scope.row.parent__title" style="color: #606266;">
                  {{ scope.row.parent__title }}
                </span>
                <span v-else style="color: #C0C4CC; font-style: italic;">
                  无父级
                </span>
              </template>
            </el-table-column>

            <!-- 优先级列 -->
            <el-table-column align="center" label="优先级" prop="star" width="180">
              <template slot-scope="scope">
                <el-rate
                  v-model="scope.row.star"
                  :max="5"
                  show-text
                  :texts="['最低', '很低', '一般', '很高', '最高']"
                  @change="handleStarChange(scope.row)"
                />
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <el-pagination
            v-if="data.length"
            background
            class="mt-pagination"
            :current-page="page"
            :page-sizes="[10, 15, 20, 50, 100]"
            :page-size="pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
          />
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script>
import { GetArticleList, Put } from '@/api/cms/topic'
import { Get as GetWebs } from '@/api/cms/web'
import { Get as GetCategories } from '@/api/cms/category'
import qs from 'qs'
import Cookies from 'js-cookie'

const webIdKey = 'cms_web_id'
const categoryIdKey = 'cms_category_id'

export function getToken(key) {
  const v = Cookies.get(key)
  return v && parseInt(v) || null
}

export function setToken(key, value) {
  if (value) {
    return Cookies.set(key, value)
  }
}

export default {
  name: 'TopicTreeArticleList',
  data() {
    return {
      // 审核状态选项（保留用于筛选）
      review_states: [
        { value: 'draft', label: '草稿' },
        { value: 'pending', label: '待审核' },
        { value: 'approved', label: '已通过' },
        { value: 'rejected', label: '已驳回' }
      ],
      review_state: '',

      // 基础数据
      project_id: this.$store.getters.projectId,
      webs: [],
      web_id: '',
      websLoading: false,

      // 分类数据
      categories: [],
      category_id: 3, // 默认官网文章
      categoriesLoading: false,

      // 筛选参数
      kwInput: '',
      progress: [0, 90], // 默认进度小于90%

      // 列表数据
      data: [],
      listLoading: false,

      // 分页参数
      pagesize: 15,
      page: 1,
      total: 0
    }
  },
  watch: {
    project_id(newValue, oldValue) {
      if (newValue !== oldValue) {
        this.getList()
      }
    }
  },
  created() {
    this.project_id = this.$store.getters.projectId
    this.web_id = getToken(webIdKey)
    this.category_id = getToken(categoryIdKey) || 3
    this.handleFetchWebs()
    this.handleFetchCategories()
    this.getList()
  },
  methods: {
    // 获取网站列表
    handleFetchWebs() {
      this.websLoading = true
      GetWebs(null, qs.stringify({ project_id: this.project_id }))
        .then(response => {
          this.websLoading = false
          this.webs = response.data.data
          if (this.webs.length && !this.web_id) {
            this.web_id = this.webs[0].id
          }
        })
        .catch(e => {
          this.websLoading = false
          this.$message.error('获取网站列表失败')
        })
    },

    // 获取分类列表
    handleFetchCategories() {
      this.categoriesLoading = true
      GetCategories()
        .then(response => {
          this.categoriesLoading = false
          this.categories = response.data.data
        })
        .catch(e => {
          this.categoriesLoading = false
          this.$message.error('获取分类列表失败')
        })
    },

    // 获取话题列表
    getList(loading) {
      if (loading === undefined) {
        loading = true
      }
      this.listLoading = loading

      GetArticleList(null, qs.stringify({
        kw: this.kwInput,
        category_id: this.category_id, // 分类ID，默认为3（官网文章）
        review_state: this.review_state,
        progress_s: this.progress[0],
        progress_e: this.progress[1],
        pagesize: this.pagesize,
        page: this.page,
        project_id: this.project_id,
        web_id: this.web_id
      }))
        .then(response => {
          this.listLoading = false
          setToken(webIdKey, this.web_id)
          setToken(categoryIdKey, this.category_id)
          this.data = response.data.data.map(m => {
            this.$set(m, 'active', false)
            return m
          })
          this.total = response.data.total || this.data.length

          if (this.data.length === 0) {
            this.$message.info('没有找到符合条件的话题')
          }
        })
        .catch(e => {
          this.listLoading = false
          console.error('获取话题列表失败:', e)
          this.$message.error('获取话题列表失败')
        })
    },

    // 搜索
    handleSearch() {
      this.page = 1
      this.getList()
    },

    // 分页大小变化
    handleSizeChange(val) {
      this.pagesize = val
      this.getList()
    },

    // 页码变化
    handlePageChange(val) {
      this.page = val
      this.getList()
    },

    // 进度提示
    progressToolTips(val) {
      return '完成进度:' + val + '%'
    },

    // 优先级变化
    handleStarChange(row) {
      const data = {
        id: row.id,
        star: row.star
      }

      Put(row.id, data)
        .then(response => {
          this.$message.success('优先级修改成功')
        })
        .catch(e => {
          this.$message.error('优先级修改失败')
          console.error('修改失败:', e)
          // 恢复原值
          this.getList(false)
        })
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.el-header {
  background-color: #fff;
  padding: 10px;
  margin-bottom: 10px;
}

.el-main {
  background-color: #fff;
  padding: 20px;
}

.topic-title {
  font-weight: 500;
  color: #303133;
}

.mt-pagination {
  float: right;
  margin-top: 20px;
}

.inline-input {
  width: 100%;
}
</style>
